package cn.kai.n4.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author kai
 * @date 2021/4/29 19:57
 * @description:
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~5
    public static int random(int amount) {
        return random.nextInt(amount) + 1;
    }
    public static void main(String[] args) {


        TicketWindow ticketWindow = new TicketWindow(1000);

        List<Thread> threadList = new ArrayList<>();

        List<Integer> amountList = new Vector<>();
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(() -> {
                int amount = ticketWindow.sell(random(5));
                amountList.add(amount);
            });
            thread.start();
            threadList.add(thread);
        }


        for (Thread thread : threadList) {

            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 统计卖出的票数和剩余票数
        log.debug("余票：{}",ticketWindow.getCount());
        log.debug("卖出的票数：{}", amountList.stream().mapToInt(i-> i).sum());

    }

    static class TicketWindow {

        private int count;


        /**
         * 初始化 票数
         *
         * @param count
         */
        public TicketWindow(int count) {
            this.count = count;
        }

        /**
         * 获取剩余票数
         *
         * @return
         */
        public int getCount() {
            return count;
        }

        /**
         * 售票
         *
         * @param amount
         * @return
         */
        public synchronized int sell(int amount) {
            if (this.count >= amount) {
                this.count -= amount;
                return amount;
            } else {
                return 0;
            }
        }


    }
}
